package cn.luckdou.WeChat.web;

import cn.luckdou.WeChat.config.WxMpConfig;
import cn.luckdou.WeChat.utils.HttpUtils;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/havezoneWechat")
public class Oauth2Controller  {

    @GetMapping("/oauth2")
    public String weChatOauth2(String code,String state,HttpServletRequest request){
        getOpenIdToSession(code,request);
        return "redirect:/"+state;
    }

    /**
     * 如果code不为空 说明是从微信授权认证过来的
     * 通过发送https请求 携带code和其他信息获取openid并存入requset.session
     * @param code
     * @param request
     */
    private void getOpenIdToSession(String code, HttpServletRequest request) {
        if(code==null || code.equals("") || code.length()<=0) return ;
        try{
            String s = HttpUtils.sendGet(WxMpConfig.getCode_url(code));
            JSONObject json = JSONObject.fromObject(s);
            String openid = json.getString("openid");
            System.out.println("openid＋＋＋＋＋＋＋＋＋＋＋＋＋＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝"+openid);
        }catch (Exception e){
            return ;
        }

    }
}
